// 游戏参数==================================================begin

// 地图参数
var MAP = {};
// 飞船参数
var AIRSHIP = {};
// 障碍物数组
var OBSTACLE = [];

// 游戏参数==================================================end

// 工具函数==================================================begin

//生成从min到max的随机数
function getRandomNumber(max, min) {
  let num = Math.floor(Math.random() * (max - min + 1)) + min;
  return num;
}
// 移动方法
function move(sCoords, cCoords, time) {
  console.log(sCoords, cCoords);
  let flog = false;
  OBSTACLE.forEach((item, index) => {
    let point = segmentsIntr(sCoords, cCoords, item.endpoint1, item.endpoint2);
    if (point != false) {
      flog = true;
      // time = ((point.X - cCoords.X) / (sCoords.X - cCoords.X)) * 2;
      time = Math.abs((Math.pow(point.X, 2) - Math.pow(cCoords.X, 2)) / 10);
      console.log(point.X - cCoords.X, time);
      $("#ME").css({
        left: point.X + "px",
        top: point.Y + "px",
        transition: "all " + time + "s"
      });
      let funTimer = setTimeout(function() {
        console.log(OBSTACLE[index]);
        let bCoords;
        if (
          sCoords.X >= OBSTACLE[index].endpoint1.X &&
          sCoords.X <= OBSTACLE[index].endpoint2.X
        ) {
          console.log(111);
          bCoords = {
            X: sCoords.X,
            Y: OBSTACLE[index].endpoint2.Y - sCoords.Y + point.Y
          };
        } else if (
          sCoords.Y >= OBSTACLE[index].endpoint1.Y &&
          sCoords.Y <= OBSTACLE[index].endpoint2.Y
        ) {
          console.log(222);
          bCoords = {
            X: OBSTACLE[index].endpoint2.X - sCoords.X + point.X,
            Y: sCoords.Y
          };
        }
        console.log(bCoords, point);
        // console.log(move());
        // move(bCoords, point);
        // move(sCoords, cCoords);
      }, time * 100);
    }
  });
  if (
    flog == false &&
    sCoords.X >= 0 &&
    sCoords.X <= 350 &&
    sCoords.Y >= 0 &&
    sCoords.Y <= 270
  ) {
    time = Math.abs((sCoords.X - cCoords.X) / 10);
    console.log(sCoords, time);
    $("#ME").css({
      left: sCoords.X + "px",
      top: sCoords.Y + "px",
      transition: "all " + time + "s"
    });
  }
}
// 判断是否相交
function segmentsIntr(a, b, c, d) {
  // 三角形abc 面积的2倍
  var area_abc = (a.X - c.X) * (b.Y - c.Y) - (a.Y - c.Y) * (b.X - c.X);
  // 三角形abd 面积的2倍
  var area_abd = (a.X - d.X) * (b.Y - d.Y) - (a.Y - d.Y) * (b.X - d.X);
  // 面积符号相同则两点在线段同侧,不相交 (对点在线段上的情况,本例当作不相交处理);
  if (area_abc * area_abd >= 0) {
    return false;
  }
  // 三角形cda 面积的2倍
  var area_cda = (c.X - a.X) * (d.Y - a.Y) - (c.Y - a.Y) * (d.X - a.X);
  // 三角形cdb 面积的2倍
  // 注意: 这里有一个小优化.不需要再用公式计算面积,而是通过已知的三个面积加减得出.
  var area_cdb = area_cda + area_abc - area_abd;
  if (area_cda * area_cdb >= 0) {
    return false;
  }
  //计算交点坐标
  var t = area_cda / (area_abd - area_abc);
  var dx = t * (b.X - a.X),
    dy = t * (b.Y - a.Y);
  return { X: a.X + dx, Y: a.Y + dy };
}

// 工具函数==================================================end

// 游戏操作==================================================begin
//添加拖拽操作
function addDrag() {
  /*+++++ 拖曳效果 ++++++
   *原理：标记拖曳状态dragging ,坐标位置iX, iY
   * mousedown:fn(){dragging = true, 记录起始坐标位置，设置鼠标捕获}
   * mouseover:fn(){判断如果dragging = true, 则当前坐标位置 - 记录起始坐标位置，绝对定位的元素获得差值}
   * mouseup:fn(){dragging = false, 释放鼠标捕获，防止冒泡}
   */
  // 是否拉动
  var dragging = false;
  // 本体与鼠标的距离
  var iX, iY;
  // 拉动距离
  var distance;
  // 目标坐标
  var sCoords = {
    X: 0,
    Y: 0
  };
  // 本体坐标
  var cCoords = {
    X: 0,
    Y: 0
  };
  // 影子坐标
  var oCoords = {
    X: 0,
    Y: 0
  };
  $("#ME").mousedown(function(e) {
    // 缓存目标
    let that = this;
    // 开启拉动状态
    dragging = true;
    // clientX/clientY鼠标坐标
    // offsetLeft/offsetTop元素坐标
    iX = e.clientX - that.offsetLeft;
    iY = e.clientY - that.offsetTop;
    cCoords.X = that.offsetLeft;
    cCoords.Y = that.offsetTop;

    // 创建影子
    // console.log($(that).attr("class").split(" ")[0])
    // let type = $(that)
    //   .attr("class")
    //   .split(" ")[0];
    // let id = "shadow";
    let Airship = $(`<div class='zwz' id='shadow'></div>`);
    $("#map").append(Airship);

    // 影子坐标
    document.onmousemove = function(e) {
      if (dragging) {
        var e = e || window.event;
        oCoords.X = e.clientX - iX;
        oCoords.Y = e.clientY - iY;
        $("#shadow").css({
          opacity: 0.5,
          left: oCoords.X + "px",
          top: oCoords.Y + "px"
        });

        // 拉动距离
        distance = Math.sqrt(
          Math.pow(oCoords.X - cCoords.X, 2) +
            Math.pow(oCoords.Y - cCoords.Y, 2)
        );
        if (distance <= 50) {
          sCoords.X = -(oCoords.X - cCoords.X) * 10 + cCoords.X;
          sCoords.Y = -(oCoords.Y - cCoords.Y) * 10 + cCoords.Y;
        }
      }
    };
  });
  // 松手执行
  $(document).mouseup(function(e) {
    // 关闭拉动状态
    dragging = false;
    // 删除影子
    $("#map")
      .children("#shadow")
      .remove();
    // console.log(cCoords, sCoords);
    move(sCoords, cCoords);
    // 判断范围条件
    // const All =
    //   sCoords.X >= 0 && sCoords.Y >= 0 && sCoords.X <= 350 && sCoords.Y <= 270;
    // const Left = sCoords.X < 0 && sCoords.Y >= 0 && sCoords.Y <= 270;
    // const Right = sCoords.X > 350 && sCoords.Y >= 0 && sCoords.Y <= 270;
    // const Top = sCoords.Y < 0 && sCoords.X >= 0 && sCoords.X <= 350;
    // const Bottom = sCoords.Y > 270 && sCoords.X >= 0 && sCoords.X <= 350;
    // const LeftTop = sCoords.X < 0 && sCoords.Y < 0;
    // const LeftBottom = sCoords.X < 0 && sCoords.Y > 270;
    // const RightTop = sCoords.X > 350 && sCoords.Y < 0;
    // const RightBottom = sCoords.X > 350 && sCoords.Y > 270;

    // // 移动长度
    // let width = sCoords.X - cCoords.X;
    // let height = sCoords.Y - cCoords.Y;
    // let length = Math.abs(width) > Math.abs(height);
    // let leftTime = Math.abs(0 - cCoords.X) / Math.abs(width);
    // let rightTime = Math.abs(350 - cCoords.X) / Math.abs(width);
    // let topTime = Math.abs(0 - cCoords.Y) / Math.abs(height);
    // let bottomTime = Math.abs(270 - cCoords.Y) / Math.abs(height);
    // 移动时间

    // console.log(All, Left, Right);
    // if (All) {
    //   move(sCoords.X, sCoords.X, 1);
    // }
    // else if (Left) {
    //   console.log("Left");
    //   console.log(segmentsIntr(sCoords.X, sCoords.Y, 0, 270));
    //   move(0, height * leftTime + cCoords.Y, leftTime);
    // } else if (Right) {
    //   console.log("Right");
    //   console.log(segmentsIntr(sCoords.X, sCoords.Y, 350, 270));
    //   move(350, height * rightTime + cCoords.Y, rightTime);
    // } else if (Top) {
    //   console.log("Top");
    //   console.log(segmentsIntr(sCoords.X, sCoords.Y, 0, 350));
    //   move(width * topTime + cCoords.X, 0, topTime);
    // } else if (Bottom) {
    //   console.log("Bottom");
    //   console.log(segmentsIntr(sCoords.X, sCoords.Y, 270, 350));
    //   move(width * bottomTime + cCoords.X, 270, bottomTime);
    // } else if (LeftTop) {
    //   console.log("LeftTop");
    //   if (length) {
    //     move(Math.abs(width * leftTime + cCoords.Y), 0, leftTime);
    //   } else {
    //     move(0, Math.abs(height * topTime + cCoords.Y), topTime);
    //   }
    // } else if (LeftBottom) {
    //   console.log("LeftBottom");
    //   if (length) {
    //     move(Math.abs(width * leftTime + cCoords.Y), 0, bottomTime);
    //   } else {
    //     move(0, Math.abs(height * bottomTime + cCoords.Y), leftTime);
    //   }
    // } else if (RightTop) {
    //   console.log("RightTop");
    //   if (length) {
    //     move(Math.abs(width * rightTime + cCoords.X), 270, topTime);
    //   } else {
    //     move(350, Math.abs(height * topTime + cCoords.Y), rightTime);
    //   }
    // } else if (RightBottom) {
    //   console.log("RightBottom");
    //   if (length) {
    //     move(Math.abs(width * rightTime + cCoords.X), 270, rightTime);
    //   } else {
    //     move(350, Math.abs(height * bottomTime + cCoords.Y), bottomTime);
    //   }
    // }
  });
}
// 游戏操作===================================================end

// 创建飞船
const CreateAirshipMe = function() {
  // 创建元素
  let Airship = $(`<div class='zwz' id='ME'></div>`);
  // 加入地图
  $("#map").append(Airship);
  // 生成飞船初始坐标
  let x = getRandomNumber(MAP.leftTop.X, MAP.width - AIRSHIP.width);
  let y = getRandomNumber(MAP.leftTop.Y, MAP.height - AIRSHIP.height);
  // 设置飞船初始坐标
  AIRSHIP.leftTop.X = x;
  AIRSHIP.leftTop.Y = y;
  $("#ME").css("top", AIRSHIP.leftTop.Y);
  $("#ME").css("left", AIRSHIP.leftTop.X);
  console.log(222);
};
// 设置地图
const CreateMap = function() {
  // 设置地图大小
  $("#map").css({
    width: MAP.width + "px",
    height: MAP.height + "px"
  });
  console.log(111);
};

// 设置参数
const setParameter = function(elem, width, height, leftTopX, LeftTopY) {
  let obj = {
    // 元素宽高
    width,
    height,
    // 元素四点坐标
    leftTop: {
      X: leftTopX,
      Y: LeftTopY
    },
    leftBottom: {
      X: leftTopX,
      Y: LeftTopY + height
    },
    rightTop: {
      X: leftTopX + width,
      Y: LeftTopY
    },
    rightBottom: {
      X: leftTopX + width,
      Y: LeftTopY + height
    }
  };

  return obj;
};

const AddObstacle = function(elem) {
  // console.log(elem);
  let segment1 = {
    endpoint1: {
      X: elem.leftTop.X,
      Y: elem.leftTop.Y
    },
    endpoint2: {
      X: elem.rightTop.X - AIRSHIP.width,
      Y: elem.rightTop.Y
    }
  };
  let segment2 = {
    endpoint1: {
      X: elem.leftTop.X,
      Y: elem.leftTop.Y
    },
    endpoint2: {
      X: elem.leftBottom.X,
      Y: elem.leftBottom.Y - AIRSHIP.height
    }
  };
  let segment3 = {
    endpoint1: {
      X: elem.rightTop.X - AIRSHIP.width,
      Y: elem.rightTop.Y
    },
    endpoint2: {
      X: elem.rightBottom.X - AIRSHIP.width,
      Y: elem.rightBottom.Y - AIRSHIP.height
    }
  };
  let segment4 = {
    endpoint1: {
      X: elem.leftBottom.X,
      Y: elem.leftBottom.Y - AIRSHIP.height
    },
    endpoint2: {
      X: elem.rightBottom.X - AIRSHIP.width,
      Y: elem.rightBottom.Y - AIRSHIP.height
    }
  };
  OBSTACLE.push(segment1, segment2, segment3, segment4);
};

// 游戏创建
const game = function() {
  console.log(000);
  // 地图参数
  MAP = setParameter(MAP, 400, 300, 0, 0);
  // 飞船参数
  AIRSHIP = setParameter(AIRSHIP, 50, 30, 0, 0);
  console.log(MAP, AIRSHIP);
  // 设置地图
  CreateMap();
  // 创建飞船
  CreateAirshipMe();
  // 添加障碍物
  AddObstacle(MAP);
  console.log(OBSTACLE);
  // 给飞船添加拖拽方法
  addDrag();
};
// 初始化游戏
game();
